//index.js
//获取应用实例
const app = getApp();
const request = require('../../utils/request.js');
const config = require('../../utils/config.js');

Page({
  data: {
    userInfo: {},
    canIUseGetUserProfile: false,
    hasUserInfo: false,
    colorTheme: app.globalData.colorTheme,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    list1: [], // 处于待处理状态的申请/邀请数（列表）
  },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: function () {
    this.onShow();
    
    wx.stopPullDownRefresh();
  },
  
  onShow: function () {
    let userInfo = wx.getStorageSync("userInfo");
    if (userInfo) {
      this.setData({
        hasUserInfo: true,
        userInfo: userInfo,
        roleList: app.roleTagsBuild(userInfo.roles)
      });
      // 加载完基础信息再加载其它信息
      let that = this;
      let url = config.SERVER_URL + 'teams/getCountThatWaitingStatus';
      let token = wx.getStorageSync('token');
      request.requestGetApi(url, token, {}, 'application/json').then((res) => {
        if(res.status === config.STATUS_OK){
          that.getCountThatWaitingStatusSucc(res);
          that.getCommentUnreadCount();
        }
      }).catch((err) => {
        app.failFun(err);
        }).finally((res) => {
          app.completeFun(res)
        })
    } else {
      this.setData({
        hasUserInfo: false,
        userInfo: null,
        roleList: null
      });
    }
  },

  /**
   * 处理收到websocket消息
   */
  acceptMsg () {
    this.getCommentUnreadCount();
    this.onShow();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options){
    const watcherIndex = app.$notify.addWatcher(this.acceptMsg);
    this.setData({ watcherIndex });
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 销毁
    app.$notify.delWatcher(this.data.watcherIndex)
  },
  
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    let that = this;
    wx.getUserProfile({
      desc: '获取昵称头像', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        that.login(res.userInfo);
      },
      fail: (err) => {
        wx.showModal({
          title: '未知错误',
          content: '请联系管理员',
        });
      }
    })
  },

  // 获取用户信息（已废弃，此处只用于官方奇怪的兼容问题）
  getUserInfo: function (e) {
    this.login(e.detail.userInfo);
  },

  // 登陆函数
  login: function(userInfo) {
    wx.showLoading({
      title: '加载ing...'
    });
    let wechatUserInfo = userInfo;
    let that = this;
    let url = config.SERVER_URL + "user/wechatLogin";
    wx.login({
      success: function (res1) {
        let params = {
          code: res1.code,
          nickName: wechatUserInfo.nickName,
          avatarUrl: wechatUserInfo.avatarUrl
        }
        request.requestPostApi(url, {}, params, "application/json").then((res) => {
            if (res.status == config.STATUS_OK) {
              let userInfo = res.data
              let token = userInfo.token.access_token
              let roleList = app.roleTagsBuild(userInfo.roles)
              wx.setStorageSync("userInfo", userInfo)
              wx.setStorageSync("token", token)
              that.onShow();
              that.setData({
                hasUserInfo: true,
                userInfo: userInfo,
                roleList: roleList
              });
              app.$notify.connectSocket();
              wx.hideLoading()

              console.log('用户token：' + token);
            }
          }).catch((err) => {
            wx.hideLoading()
            if (!err.showModal) {
              wx.showModal({
                title: '登录出错',
                content: '未知异常',
                showCancel: false
              })
            }
            wx.showModal({
              title: '登录出错',
              content: err.message,
              showCancel: false
            });
          }).finally((res) => {
            app.completeFun(res)
          })
      },
      complete: function (e) {
        wx.hideLoading();
      }
    });
  },

  // 校验登录&跳子页
  checkLoginAndNavigate: function (url) {
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      wx.navigateTo({
        url: url
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '需要登录',
        showCancel: false
      })
    }
  },

  // 跳转到个人信息页面
  goUserInfo: function (e) {
    this.checkLoginAndNavigate('./userinfo/userinfo');
  },

  // 跳转到认证申请界面
  goAuthApply: function (e) {
    this.checkLoginAndNavigate('./auth-apply/auth-apply');
  },

  // 跳转到申请/邀请列表
  goApplyAndInvitation: function (e) {
    this.checkLoginAndNavigate('./apply-invitation-list/apply-invitation-list?countList=' + this.data.list1.join());
  },

  // 跳转到团队管理界面
  goManageTeam: function (e) {
    this.checkLoginAndNavigate('./manage-team/manage-team');
  },

  // 跳转到我的收藏列表
  goCollectionList: function (e) {
    this.checkLoginAndNavigate('./collection-list/collection-list');
  },

  // 跳转到消息中心页面
  goMessageCenter: function(e) {
    this.checkLoginAndNavigate('./message-center/message-center');
  },

  // 跳转到消息中心页面
  goAppointmentsList: function(e) {
    this.checkLoginAndNavigate('./appointment-list/appointment-list');
  },

  // 登出
  logout: function () {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗',
      success (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '登出ing'
          });
          app.$notify.closeSocket();
          wx.setStorageSync('userInfo', null);
          wx.setStorageSync('token', null);
          that.setData({
            list1: [],
            countThatWaitingStatus: 0
          })
          that.onShow();
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      },
      complete (res) {
        wx.hideLoading();
      }
    })
  },

  // 获取还处于待处理状态的消息数列表
  getCountThatWaitingStatusSucc: function (res) {
    let countList = res.data;
    let sum = parseInt(countList[1]) + parseInt(countList[3]);
    let countThatWaitingStatus = (sum > 99) ? '99+' : sum;
    this.setData({
      countThatWaitingStatus: countThatWaitingStatus,
      list1: countList
    })
  },

  // 获取待未读消息数量
  getCommentUnreadCount(){
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'comment/getCommentUnreadCount';
    request.requestGetApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        this.setData({
          commentUnreadCound: res.data[0] + res.data[1]
        });
      }
    }).catch(err=>{
      app.failFun(err);
    });
  }
})
